package com.glebusheg.ui
{
	import com.greensock.easing.Cubic;
	import com.greensock.TweenLite;
	
	import com.glebusheg.data.ShopGroupData;
	
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author Gleb Volkov
	 */
	public class Accordion extends Sprite 
	{
		private var _panels:Vector.<Panel>;
		
		private var _width:Number;
		private var _height:Number;
		
		private var _navH:Number;
		private var _panelH:Number;
		
		private var _curPanelNum:int = 0;
		
		public function Accordion(width:Number, height:Number, total:int, navHeight:Number) 
		{
			_width = width;
			_height = height;
			_navH = navHeight;
			
			_panelH = height - total * navHeight;
			
			_curPanelNum = total - 1;
			
			// залить либо одним тоном, текстурой или картинкой целиком
/*			graphics.beginFill(0xCCCCCC);
			graphics.drawRect(0, 0, width, height);
			graphics.endFill();*/
			
			var rect:Rectangle = new Rectangle(0, 0, _width, _height);
			scrollRect = rect;
			
			mouseEnabled = false;
			
			_panels = new Vector.<Panel>();
		}
		
		public function addPanel(data:ShopGroupData):void
		{
			var header:Sprite = getDefaultBase(_navH);
			var content:Sprite = getDefaultBase(_panelH);
			
			var panel:Panel = new Panel(header, content, data.items);
			panel.y = _panels.length * _navH;
			
			panel.addEventListener(PanelEvent.SELECT, onPanelSelect);
			
			addChild(panel);
			_panels.push(panel);
			
			var panelNum:int = _panels.length - 1;
			selectPanel(panelNum, true);
		}
		
		private function onPanelSelect(e:PanelEvent):void 
		{
			selectPanel(_curPanelNum, true);
			//_curPanelNum = (e) ? _panels.indexOf(e.panel) : 0;
			_curPanelNum = _panels.indexOf(e.panel);
			selectPanel(_curPanelNum, false);
			
			var i:int, panel:Panel;
			for (i = _curPanelNum + 1; i < _panels.length; i++) 
			{
				panel = _panels[i];
				TweenLite.to(panel, 0.5, { y:_height - (_panels.length - i) * _navH, ease:Cubic.easeOut } );
			}
			for (i = 1; i <= _curPanelNum; i++) 
			{
				panel = _panels[i];
				TweenLite.to(panel, 0.5, { y:i * _navH, ease:Cubic.easeOut } );
			}
		}

		private function selectPanel(num:int, enable:Boolean):void
		{
			_panels[num].enabled = enable;
		}
		
		public function reset():void
		{
			// onPanelSelect(null);
			if (_panels && _panels.length > 0)
			{
				_panels[0].forceSelect();
			}
		}
		
		public function destroy():void
		{
			for each (var panel:Panel in _panels) 
			{
				panel.removeEventListener(PanelEvent.SELECT, onPanelSelect);
				panel.destroy();
				removeChild(panel);
			}
			_panels.length = 0;
		}
		
		private function getDefaultBase(h:Number):Sprite
		{
			var base:Sprite = new Sprite();
			var randCol:uint = int(Math.random() * 0xFFFFFF);
			base.graphics.beginFill(randCol, 1);
			base.graphics.drawRect(0, 0, _width, h);
			base.graphics.endFill();
			return base;
		}

	}

}